package com.google.code.jbauble.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.google.code.jbauble.dao.mysql.MysqlDatastore;
import com.google.code.jbauble.dao.mysql.MysqlNative;

public class DatastoreManager {
	public static String DEFAULT_DATASTORE = "default";
	private static Datastore defaultDatastore;
	private static Map<String, Datastore> datastores = new HashMap();
	
	public static Datastore getDefaultDatastore() {
		return defaultDatastore;
	}
	
	public static Datastore getDatastore(String name) {
		if (name != null && name.equals(DEFAULT_DATASTORE)) {
			return defaultDatastore;
		}
		else {
			return datastores.get(name);
		}
	}
	
	public static void addDatastore(String name, Datastore ds) {
		if (name != null && name.equals(DEFAULT_DATASTORE)) {
			defaultDatastore = ds;
		}
		else {
			datastores.put(name, ds);
		}
	}
	
	public static String DB_TYPE = "db.type";
	public static String DB_DBNAME = "db.dbName";
	public static String DB_USER = "db.user";
	public static String DB_PWD = "db.pwd";
	public static String DB_MINPOOL = "db.minPool";
	public static String DB_MAXPOOL = "db.maxPool";
	public static String DB_PARTITION = "db.partition";
	public static String DB_PACKAGES = "db.packages";
	
	public static void initDatabase(String env, Properties p) {
		if (p.getProperty(DB_TYPE) == null 
				|| p.getProperty(DB_PACKAGES) == null 
				|| p.getProperty(DB_PACKAGES).equals(""))
			return;
		String url = p.getProperty("db." + env + ".url");
		Datastore ds = new MysqlDatastore(
				new MysqlNative(url, 
						p.getProperty(DB_DBNAME),
						p.getProperty(DB_USER),
						p.getProperty(DB_PWD),
						Integer.parseInt(p.getProperty(DB_MINPOOL)),
						Integer.parseInt(p.getProperty(DB_MAXPOOL)),
						Integer.parseInt(p.getProperty(DB_PARTITION))),
				getPackages(p));
		
		addDatastore(DEFAULT_DATASTORE, ds);
	}

	private static String[] getPackages(Properties p) {
		String ps = p.getProperty(DB_PACKAGES);
		if (ps == null || ps.equals(""))
			return null;
		
		return ps.split(",");
	}
}
